package tw.cating.karmasaver.rss;

import tw.cating.karmasaver.R;
import tw.cating.karmasaver.intef.dataChangedListener;
import tw.cating.karmasaver.rss.structer.rssNode;
import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class rssAdapter extends BaseAdapter{
	rssHandler mHandler = new rssHandler();
	rssSiteAdapter mSiteAdapter = null;
	Context mContext = null;
	dataChangedListener l = null;
	
	private static final int MSG_DATACHANGED = 1;
	Handler mMsgHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			switch (msg.what) {
			case MSG_DATACHANGED:
				notifyDataSetChanged();
				if (l != null)
					l.onDataChanged();
				break;
				
			}
			super.handleMessage(msg);
		}
	};
	
	public rssAdapter(Context context) {
		mContext = context;
		mSiteAdapter = new rssSiteAdapter(mContext);
		reflash();

	}
	
	public rssAdapter(Context context, dataChangedListener listener) {
		mContext = context;
		mSiteAdapter = new rssSiteAdapter(mContext);
		l = listener;
		reflash();
	}
	
	public void setDataChangedListener(dataChangedListener listener) {
		l = listener;
	}
	
	public void reflash() {
		Thread t = new Thread() {
			public void run() {
				mSiteAdapter.reflash();
				mHandler.reset();
				for (int i = 0; i < mSiteAdapter.getCount(); i ++) {
					mHandler.parserUrl((rssSiteAdapter.rssSite)mSiteAdapter.getItem(i));
				}
				mMsgHandler.sendEmptyMessage(MSG_DATACHANGED);
			}
		};
		t.start();
	}
	
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		rssNode node = (rssNode)getItem(position);
		if (convertView == null) {
			convertView = ((Activity)mContext).getLayoutInflater().inflate(R.layout.listitem, null);
		}
		TextView text = (TextView)convertView.findViewById(R.id.rssdesc);
		text.setText(node.getDescription());
		TextView rssFrom = (TextView)convertView.findViewById(R.id.rssfrom);
		rssFrom.setText(node.getFrom());
		return convertView;
	}

	public int getCount() {
		// TODO Auto-generated method stub
		return mHandler.getCount();
	}

	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return mHandler.getItem(position);
	}

	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}
}
